/* global window */
import { message } from 'antd'
import api from 'api'
import modelExtend from 'dva-model-extend'
import { pathMatchRegexp } from 'utils'
import { pageModel } from 'utils/model'
import moment from 'moment'

const { queryAllMsg, queryTodayMsg, fetchdetail } = api

const regionstore = {
  index: 0,
  data: [],
  start: moment()
    .subtract(1, 'month')
    .format('YYYY-MM-DD'),
  end: moment().format('YYYY-MM-DD'),
  cached: { Device: {}, Project: {}, User: {} },
}

export default modelExtend(pageModel, {
  namespace: 'msgs',

  state: {
    ...regionstore,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathMatchRegexp('/msgs', location.pathname)) {
          let payload = { index: 0, start: '', end: '' }
          let todaydate = moment().format('YYYY-MM-DD')
          if (location.query) {
            if (location.query.index !== undefined) {
              payload.index = location.query.index
            }
            if (location.query.start) {
              payload.start = location.query.start
            } else {
              payload.start = moment()
                .subtract(1, 'month')
                .format('YYYY-MM-DD')
            }
            if (location.query.end) {
              payload.end = location.query.end
            } else {
              payload.end = todaydate
            }
          }
          dispatch({
            type: 'query',
            payload: {
              ...payload,
            },
          })
        }
      })
    },
  },

  effects: {
    *clearstore({ payload = {} }, { call, put, select }) {
      yield put({
        type: 'updateState',
        payload: { ...regionstore },
      })
    },
    *query({ payload }, { call, put }) {
      let todaydate = moment().format('YYYY-MM-DD')
      let todaydata = [],
        historydata = []
      if (todaydate == payload.end) {
        const { result } = yield call(queryTodayMsg, payload)
        todaydata = result
      }
      const { result } = yield call(queryAllMsg, payload)
      historydata = result
      let tmpdata = todaydata.concat(historydata)
      let data = []
      for (let index in tmpdata) {
        let item = tmpdata[index]
        if (!item) continue
        const { Msgs, TimeToken } = item
        for (let index2 in Msgs) {
          let item2 = Msgs[index2]
          if (!item2) continue
          const { msg, time } = item2
          try {
            data.push({
              msg: JSON.parse(msg),
              time,
            })
          } catch {
            console.log('parse failed')
          }
        }
      }
      yield put({ type: 'updateState', payload: { ...payload, data } })
      yield put({ type: 'fetchdetail', payload: { page: 1, data } })
    },
    *fetchdetail({ payload }, { call, select, put }) {
      const { cached } = yield select(_ => _.msgs)
      //
      const { page, data } = payload
      let needfetch = []
      let filtered = data.slice((page - 1) * 10, (page - 1) * 10 + 1)
      for (let ind in filtered) {
        let item = filtered[ind]
        if (!item) continue
        const { msg, time } = item
        if (!msg) continue
        const { Params } = msg
        for (let id2 in Params) {
          let item2 = Params[id2]
          if (!item2) continue
          const { type, params } = item2
          if (type == 'Words' || !params) continue
          let cache = cached[type]
          if (!cache || !cache[params.objectId]) {
            needfetch.push(item2)
          }
        }
      }
      if (needfetch && needfetch.length > 0) {
        const { result } = yield call(fetchdetail, {
          params: JSON.stringify(needfetch),
        })
        for (let ina in result) {
          let itemt = result[ina]
          if (!itemt) continue
          const { type, params } = itemt
          if (type == 'Words' || !params) continue
          const { objectId } = params
          if (objectId) cached[type][objectId] = itemt
        }
        yield put({ type: 'updateState', payload: { cached } })
      }
    },
  },

  reducers: {},
})
